import {delLocalStorage} from '../../utils/localStorage'
import router from '../../router/index'
import {LOGOUT, MOVEMENU, JUMP, INITMQTT, ONCONNECTTIONLOST, ONMESSAGEARRIVED, ONCONNECT, ONSHOWMSG, ONCLOSEMSG} from '../types'
import mqtt from 'mqtt'
const state = {
  data: {
    drawer: true,
    errorCode: '',
    errorInfo: '',
    isRouterAlive: true,
    items: [
      { icon: 'dashboard', text: 'DashBoard', url: 'dashboard' }
    ],
    showSnackbar: false,
    position: 'center',
    duration: 1000,
    isInfinity: false,
    message: '',
    client: '',
    msgflg: false,
    msgtype: '',
    msg: ''
  }
}

const mutations = {
  [MOVEMENU]: (state) => {
    state.data.drawer = !state.data.drawer
  },
  [LOGOUT]: (state) => {
    let r = confirm('确认退出？')
    if (r === true) {
      delLocalStorage('admin-token')
      router.push({path: '/login'})
    }
  },
  [JUMP]: (state, playload) => {
    router.push({ path: playload })
  },
  [INITMQTT]: (state) => {
    // state.data.showSnackbar = true
    // state.data.message = 'init'
    state.data.client = mqtt.connect('ws://10.42.0.20', {
      username: 'aaa',
      password: '111qqq!',
      protocolId: 'MQTT',
      port: 15675,
      path: '/ws',
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      reconnectPeriod: 1000,
      connectTimeout: 30 * 1000,
      keepalive: 60
    })
    state.data.client.on('connect', function () {
      state.data.client.subscribe('user')
      // state.data.client.publish('user', 'Hello mqtt')
    })
    state.data.client.on('message', function (topic, message) {
      // message is Buffer
      console.log(message.toString())
      state.data.showSnackbar = true
      state.data.message = message.toString()
      // state.data.client.end()
    })
  },
  [ONCONNECTTIONLOST]: (state) => {

  },
  [ONMESSAGEARRIVED]: (state) => {

  },
  [ONCONNECT]: (state) => {

  },
  [ONSHOWMSG]: (state, param) => {
    state.data.msgflg = true
    state.data.msgtype = param.type
    state.data.msg = param.text
  },
  [ONCLOSEMSG]: (state) => {
    state.data.msgflg = false
  }
}

const actions = {
  [MOVEMENU]: ({commit}) => {
    commit('moveMenu')
  },
  [LOGOUT]: ({commit}) => {
    commit('logout')
  },
  [JUMP]: ({commit}, playload) => {
    commit('jump', playload)
  },
  [INITMQTT]: ({commit}) => {
    commit('initMqtt')
  },
  [ONCONNECTTIONLOST]: ({commit}) => {
    commit('onConnectionLost')
  },
  [ONMESSAGEARRIVED]: ({commit}) => {
    commit('onMessageArrived')
  },
  [ONCONNECT]: ({commit}) => {
    commit('onConnect')
  },
  onShowmsg: ({commit}, param) => {
    commit('onShowMsg', param)
  },
  onClosemsg: ({commit}) => {
    commit('onCloseMsg')
  }
}

export default {
  state,
  mutations,
  actions
}
